﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Configuration;
using VSM.Utils;

namespace VSM
{
    public partial class PartsPOPendingEdit : System.Web.UI.Page
    {
        public static DataTable dtContents;
        public static DataTable dtHeader;
        private static GeneralFunctions GF = null;
        private string TblHeaderName = "OPOR";
        private string TblLineName = "POR1";
        private string CurrentPageUrl = "/Business/Purchasing/CreatePO.aspx";
        private string HeaderKeyName = "DocEntry";

        private String TargetPageUrlGRPO = "/Business/Purchasing/GoodsReceiptPO.aspx";
        private String TargetPageUrlAPINV = "/Business/Purchasing/APInvoice.aspx";

        #region FileStreamObj
        protected Stream FileStreamObj
        {
            get { return (Stream)Session["FileStreamObj"]; }
            set { Session["FileStreamObj"] = value; }
        }
        #endregion

        #region FileLines
        protected ArrayList FileLines
        {
            get { return (ArrayList)ViewState["FileLines"]; }
            set { ViewState["FileLines"] = value; }
        }
        #endregion

        #region MRP
        private string _mrp = string.Empty;
        private string _mrpPOId = string.Empty;
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../Login.aspx");
                }
             
                //Convert MRPPO to actual PO
                if (Request.QueryString["MRPPO"] != null)
                {
                    _mrp = Request.QueryString["MRPPO"];
                }
                if (Request.QueryString["MRPPOID"] != null)
                {
                    _mrpPOId = Request.QueryString["MRPPOID"];
                }
                if (!IsPostBack)
                {
                    string dbType =Utils.AppConstants.DEALER;
                    GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    //ClearScreen();

                    String poId = Request.QueryString["po_id"];
                    if (!String.IsNullOrEmpty(poId))
                    {
                        LoadData(poId, ConvertDocType.Get2String(DocType.PURCHASE_ORDER));
                        if (lblStatus.Text == "Closed")
                            SetScreenStatus("Close");
                        else if (lblStatus.Text == "O")
                            SetScreenStatus("Update");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }

                    String BaseEntry = Request.QueryString["base_entry"];
                    if (!String.IsNullOrEmpty(BaseEntry) || _mrpPOId.Length>0)
                    {
                        String BaseType = Request.QueryString["base_type"];
                        LoadData(BaseEntry, BaseType);
                    }
                    if (_mrp.Length > 0)
                    {
                        this.btnSave.Visible = true;
                        this.btnCancel.Visible = true;
                        this.btnAddItems.Visible = false;
                        this.btnImport.Visible = false;
                        this.btnApprove.Visible = false;
                    }
                    if (Request.QueryString["mess"] != null)
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            this.ddlAppStatus.Enabled = false;
            this.ddlPOType.Enabled = false;
            this.txtConpersonName.Enabled = false;
            this.txtDelDate.Enabled = false;
            this.txtPODate.Enabled = false;
            this.txtPONo.Enabled = false;
            this.txtVendorCode.Enabled = false;
            this.txtVendorName.Enabled = false;
            this.grvPO.Enabled = false;
            this.txtPostingDate.Enabled = false;
            this.imgDeldate.Visible = false;
            this.imgPODate.Visible = false;
            this.imgPostingDate.Visible = false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvPO.PageIndex = e.NewPageIndex;
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            BindData(tblPOR1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvPO.EditIndex = -1;
                    //BindData((DataTable)Session["POR1Table"]);
                    BindData(tb);
                    //CalcTotal(((DataTable)Session["POR1Table"]));
                    CalcTotal(tb);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";

                string dbType =  Utils.AppConstants.DEALER;
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                Label lblModel = (Label)e.Row.FindControl("lblModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (lblModel != null) ddlModel.SelectedValue = lblModel.Text;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, lblModel.Text);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    Label lblProduct = (Label)e.Row.FindControl("lblProduct");
                    if (lblProduct != null) ddlProduct.SelectedValue = lblProduct.Text;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = GF.GetColorList(dbType);
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    Label lblColor = (Label)e.Row.FindControl("lblColor");
                    if (lblColor != null) ddlColor.SelectedValue = lblColor.Text;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void DisableControl()
        {
            
            this.btnSave.Visible = false;
            this.btnAddItems.Visible = false;
            this.txtPODate.Enabled = false;
            this.txtDelDate.Enabled = false;
            this.txtRemarks.Enabled = false;
            
            this.btnCancel.Visible = false;
            this.grvPO.Columns[0].Visible = false;
            for (int i = 0; i < this.grvPO.Rows.Count; i++)
            {
                TextBox txtOrderQuantity = (TextBox)this.grvPO.Rows[i].FindControl("txtOrderQuantity");
                txtOrderQuantity.Enabled = false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadSupplierAmount()
        {
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            /*
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }*/
        }

        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtUnitPrice.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void txtDiscPrcnt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
                if (txtDiscPrcnt.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtDiscPrcnt.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
                        updateRowTotalPrice(rupdate[0], "DiscPrcnt");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadOrderWareHouse()
        {
            try
            {
                
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dr"></param>
        private DataRow FillShipToAddress(string outletId, bool isFill)
        {
            try
            {
                if (outletId.Length > 0)
                {
                    MasterData obj = new MasterData();
                    DataSet tbWareHouse = null; // obj.GetWareHouseAddress(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode);
                    if (tbWareHouse != null && tbWareHouse.Tables.Count > 0)
                    {

                        DataRow[] r = tbWareHouse.Tables[0].Select("WhsCode = '" + outletId + "'");
                        if (r.Length > 0)
                        {
                            if (isFill)
                            {
                                StringBuilder shipTo = new StringBuilder();
                                shipTo.AppendLine(r[0]["Block"].ToString());
                                shipTo.AppendLine(r[0]["Street"].ToString() + " " + r[0]["City"].ToString());
                                shipTo.AppendLine(r[0]["Country"].ToString() + " " + r[0]["ZipCode"].ToString());
                            }
                            else
                            {
                                return r[0];
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            this.grvPO.EditIndex = e.NewEditIndex;
            BindData((DataTable)Session["POR1Table"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            this.grvPO.EditIndex = -1;
            BindData((DataTable)Session["POR1Table"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvPO.EditIndex = -1;
                    BindData((DataTable)Session["POR1Table"]);
                    CalcTotal(((DataTable)Session["POR1Table"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                    }

                    this.grvPO.EditIndex = -1;

                    BindData(tb);
                    CalcTotal(tb);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void BindData(DataTable tblData)
        {
            Session["POR1Table"] = tblData;
            this.grvPO.DataSource = tblData;
            this.grvPO.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
                    DataTable tblPOR1 = (DataTable)Session["POR1Table"];
                    string dbType = Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblPOR1 != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        DataRow rowNew = tblPOR1.NewRow();
                                        rowNew["No"] = (tblPOR1.Rows.Count + 1).ToString();
                                        rowNew["ItemCode"] = item.Key;
                                        rowNew["Dscription"] = item.Value;
                                        rowNew["U_Model"] =
                                        rowNew["U_Product"] =
                                        rowNew["U_Color"] = string.Empty;
                                        rowNew["Quantity"] = 1;
                                        rowNew["PriceBefDi"] = 0;
                                        rowNew["DiscPrcnt"] = 0;
                                        rowNew["PriceBefDi"] = 0;
                                        rowNew["TaxCode"] = "";
                                        rowNew["VatPrcnt"] = 0;
                                        tblPOR1.Rows.Add(rowNew);
                                    }

                                    if (tblPOR1.Rows.Count > 0)
                                    {
                                        //Update Price
                                        foreach (DataRow dr in tblPOR1.Rows)
                                            updateRowTotalPrice(dr, "");
                                        CalcTotal(tblPOR1);
                                    }
                                    //ReLoad Data
                                    //BindData(tblPOR1);
                                }
                            }
                            //ReLoad Data
                            BindData(tblPOR1);
                            break;

                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            this.txtVendorCode.Text = ((Label)row.FindControl("lblCardCode")).Text;
                            this.txtVendorName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            if (tblPOR1 != null)
                            {
                                tblPOR1.Rows.Clear();
                            }
                            Session["ChosenBP"] = null;
                            //tblPOR1 = LoadSetupItem(poDate, tblPOR1);
                            //LoadSupplierAmount();
                            this.btnAddItems.Visible = true;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string poId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            LoadData(poId, doctype);
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="tblIPO"></param>
        /// <returns></returns>
        private DataTable LoadSetupItem(DateTime poDate, DataTable tblIPO)
        {
            MasterData obj = new MasterData();
            DataSet dsItem = null; // obj.GetSupplierItemSetup(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, this.txtVendorCode.Text, "");
            Dictionary<string, string> dicItem = new Dictionary<string, string>();
            if (dsItem != null && dsItem.Tables.Count > 0)
            {
                dsItem.Tables[0].Columns.Add("Quantity");
                DataSet dsAllPrice = null; // obj.GetAllItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, POR1TableDate, this.txtVendorCode.Text,dsItem.Tables[0]);
                foreach (DataRow r in dsItem.Tables[0].Rows)
                {
                    if (!dicItem.ContainsKey(r["ItemCode"].ToString()))
                    {
                        dicItem.Add(r["ItemCode"].ToString(), r["ItemName"].ToString());
                    }
                    if (dsAllPrice != null && dsAllPrice.Tables.Count > 0)
                    {
                        foreach (DataRow row in dsAllPrice.Tables[0].Rows)
                        {
                            if (r["ItemCode"].ToString() == row["ItemCode"].ToString())
                            {
                                DataRow rowNew = tblIPO.NewRow();
                                rowNew["ItemCode"] = r["ItemCode"].ToString();
                                rowNew["Dscription"] = r["ItemName"].ToString();
                                rowNew["LB"] = r["LB"].ToString();
                                rowNew["MinStock"] = Math.Round(decimal.Parse(r["MinQty"].ToString()), 2);
                                rowNew["MaxStock"] = Math.Round(decimal.Parse(r["MaxQty"].ToString()), 2);
                                rowNew["BuyUnitMsr"] = row["BuyUnitMsr"];
                                rowNew["Quantity"] = decimal.Parse("0").ToString("#,##0.00");
                                rowNew["ReceivedQty"] = row["ReceivedQty"];
                                if (row["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                                {
                                    rowNew["Price"] = (decimal.Parse(row["NumInBuy"].ToString()) * decimal.Parse(row["Price"].ToString())).ToString("#,##0.00");
                                }
                                else
                                {
                                    rowNew["Price"] = decimal.Parse(row["Price"].ToString()).ToString("#,##0.00");
                                }
                                rowNew["LineTotal"] = decimal.Parse(row["LineTotal"].ToString()).ToString("#,##0.00");
                                rowNew["VatgroupPu"] = row["VatgroupPu"];
                                rowNew["Rate"] = row["Rate"];
                                rowNew["ShipType"] = row["ShipType"];
                                rowNew["TrnspName"] = row["TrnspName"];
                                DataRow[] rCheck = tblIPO.Select("ItemCode='" + r["ItemCode"].ToString() + "'");
                                if (rCheck.Length == 0)
                                {
                                    tblIPO.Rows.Add(rowNew);
                                }
                            }
                        }
                    }
                    //tblIPOR1Table = AddNewItem(tblIPOR1Table, poDate, r["ItemCode"].ToString(), r["ItemName"].ToString(), r["LB"].ToString(), decimal.Parse(r["MinQty"].ToString()), decimal.Parse(r["MaxQty"].ToString()), this.txtVendorCode.Text, 0);
                }
            }
            Session["ChosenItem"] = dicItem;
            //ReLoad Data
            BindData(tblIPO);
            if (tblIPO.Rows.Count > 0)
            {
                //Update Price
                //UpdatePrice();
                CalcTotal(tblIPO);
            }
            this.btnSave.Visible = true;
            this.btnAddItems.Visible = true;
            return tblIPO;
        }
        /// <summary>
        /// 
        /// </summary>
        private void UpdatePrice()
        {
            try
            {
                //Update Price
                foreach (DataRow r in ((DataTable)Session["POR1Table"]).Rows)
                {
                    GetPrice(r);
                }
                BindData((DataTable)Session["POR1Table"]);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// Update Price
        /// </summary>
        /// <param name="r"></param>
        private void GetPrice(DataRow r)
        {
            try
            {
                DataSet ds = GetDataItem( DateTime.Parse(this.txtPODate.Text.Trim()), r["ItemCode"].ToString(), this.txtVendorCode.Text, double.Parse(r["Quantity"].ToString()));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                    {
                        r["Price"] = (decimal.Parse(ds.Tables[0].Rows[0]["NumInBuy"].ToString()) * decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    else
                    {
                        r["Price"] = decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    r["LineTotal"] = (double.Parse(r["Price"].ToString()) * double.Parse(r["Quantity"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                }
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblIPO"></param>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="itemName"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataTable AddNewItem(DataTable tblPO, DataRow drDefaultLine, string ItemCode, string Dscription, string Model, string Color)
        {
            try
            {
                if (drDefaultLine != null && drDefaultLine.ItemArray.Length > 0)
                {
                    DataRow rowNew = tblPO.NewRow();
                    rowNew["ItemCode"] = ItemCode;
                    rowNew["Dscription"] = Dscription;
                    rowNew["U_Model"] = Model;
                    rowNew["U_Color"] = Color;
                    rowNew["Quantity"] = 1;

                    rowNew["PriceBefDi"] = drDefaultLine["UnitPrice"];
                    rowNew["DiscPrcnt"] = drDefaultLine["Discount"];
                    rowNew["Price"] = drDefaultLine["UnitPrice"];

                    rowNew["TaxCode"] = drDefaultLine["TaxCode"];
                    rowNew["VatPrcnt"] = drDefaultLine["TaxRate"];

                    DataRow[] rCheck = tblPO.Select("ItemCode='" + ItemCode + "'");
                    if (rCheck.Length == 0)
                    {
                        tblPO.Rows.Add(rowNew);
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return tblPO;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void CalcTotal(DataTable tb)
        {
            try
            {
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["VatPrcnt"] != null && row["VatPrcnt"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["VatPrcnt"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }
                documentTotal += subTotal + gstTotal;
                this.lblDocumentTotal.Text = string.Format("{0:C}", Math.Round(documentTotal, 2));
                this.lblTaxAmount.Text = string.Format("{0:C}", Math.Round(gstTotal, 2));
                this.lblSubTotal.Text = string.Format("{0:C}", Math.Round(subTotal, 2));
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        {
            try
            {
                MasterData obj = new MasterData();
                DataSet ds = new DataSet();
                ds = null; // obj.GetItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, itemCode, venderCode, quantity);
                return ds;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        private string CheckDate()
        {
            if (this.txtDelDate.Text.Trim().Length > 0 && this.txtPODate.Text.Trim().Length > 0)
            {
                if (Utils.AppConstants.isDateTime(this.txtPODate.Text) && Utils.AppConstants.isDateTime(this.txtDelDate.Text))
                {
                    if (Utils.AppConstants.ConvertToDate(this.txtPODate.Text).Date > Utils.AppConstants.ConvertToDate(this.txtDelDate.Text).Date)
                    {
                        return "Delivery Date cannot earliar than PO Issue Date.";
                    }
                }
                else
                {
                    return "PO Issue Date or Expected Delivery Date is incorrect format.";
                }
            }
            else
            {
                return "PO Issue Date or Expected Delivery Date is not Blank.";
            }
            return string.Empty;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            /*try
            {
               string errMess =  CheckDate();
               if (errMess.Length > 0)
               {
                   this.lblError.Text = errMess;
                   this.lblError.Visible = true;
                   return;
               }
                this.lblError.Visible = false;
                this.lblError.Text = "";
                DataSet dsData = new DataSet();
                dsData = CollectDataPO(false);
                if (dsData != null)
                {
                    MasterData obj = new MasterData();
                    DataSet dsResult = null;//obj.CreatePO(_companyCode, this.hdnIsUpdate.Value, _isPO, dsData, false, _docEntry, this.txtVendorCode.Text, "");
                    if (dsResult != null && dsResult.Tables.Count > 0 && dsResult.Tables[0].Rows.Count > 0)
                    {
                        if ((int)dsResult.Tables[0].Rows[0]["ErrCode"] != 0)
                        {
                            string err = dsResult.Tables[0].Rows[0]["ErrMsg"].ToString();
                            if (err.Trim() == "The device is not ready.")
                            {
                                err = "System is processing another request. Pls try again later.";
                            }
                            this.lblError.Text = err;
                        }
                        else
                        {
                            this.lblError.Text = "Operation complete successful!";

                            if (this.hdnIsUpdate.Value == "0")
                            {
                                //ResetPage();
                            }
                            
                        }
                    }
                    else
                    {
                        this.lblError.Text = "System is processing another request. Pls try again later.";
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;*/
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value == "C") // || this.hdnIsCreatedSO.Value.Equals("true")
                {
                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtOrderQuantity");
                    TextBox txtUnitPrice = (TextBox)myRow.FindControl("txtUnitPrice");
                    TextBox txtDiscPrcnt = (TextBox)myRow.FindControl("txtDiscPrcnt");

                    LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
                    if(lnkDelete != null) lnkDelete.Enabled = false;

                    if (txtQuantity != null)
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        txtQuantity.BorderStyle = BorderStyle.None;
                    }
                    if (txtUnitPrice != null)
                    {
                        txtUnitPrice.ReadOnly = true;
                        txtUnitPrice.BackColor = System.Drawing.Color.Transparent;
                        txtUnitPrice.BorderStyle = BorderStyle.None;
                    }
                    if (txtDiscPrcnt != null)
                    {
                        txtDiscPrcnt.ReadOnly = true;
                        txtDiscPrcnt.BackColor = System.Drawing.Color.Transparent;
                        txtDiscPrcnt.BorderStyle = BorderStyle.None;
                    }
                }

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
                this.btnAddItems.Enabled = true;
            }
            catch
            {
                this.btnAddItems.Enabled = false;
            }
            UpdatePrice();
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType =  Utils.AppConstants.DEALER;
                String requestXML = _collectData();
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML,ConvertDocType.Get2String(DocType.PURCHASE_ORDER), txtPONo.Text, hdnIsUpdate.Value.Equals("true"), dbType);
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    MasterData obj = new MasterData();
                    string errorMess = obj.UpdatePOMRPStatus(_mrpPOId, dbType, (DataSet)Session["OpenOrderQty"]);
                    if (_mrp.Length > 0)
                    {
                        Response.Redirect("/Business/Purchasing/CreatePO.aspx?mess=1");
                    }
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    //ClearScreen();
                    dtContents = null;
                    LoadDefault();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Taxcode");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");
            dt.Columns.Add("BaseType");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();

                    if (dtContent.Columns.Contains("LineNum")) row["LineNum"] = dr["LineNum"];
                    row["No"] = dr["No"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Taxcode"] = dr["Taxcode"];
                    if (dtContent.Columns.Contains("VatPrcnt")) row["VatPrcnt"] = dr["VatPrcnt"];
                   
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["UomCode"] = dr["UomCode"];
                    row["Quantity"] = dr["Quantity"];
                    row["PriceBefDi"] = dr["PriceBefDi"];
                    row["DiscPrcnt"] = dr["DiscPrcnt"];
                    row["Price"] = dr["Price"]; // Price After Discount
                    row["LineTotal"] = dr["LineTotal"];

                    if (dtContent.Columns.Contains("BaseType"))
                    {
                        row["BaseType"] = dr["BaseType"];
                    }
                    if (dtContent.Columns.Contains("BaseEntry"))
                    {
                        row["BaseEntry"] = dr["BaseEntry"];
                    }
                    if (dtContent.Columns.Contains("BaseLine"))
                    {
                        row["BaseLine"] = dr["BaseLine"];
                    }
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadDefault()
        {
            this.lblStatus.Text = "Open";
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDelDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtPODate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtPONo.Text = 
            this.txtConpersonName.Text = string.Empty;
            //this.txtVendorCode.Text = 
            //this.txtVendorName.Text =
            this.ddlPOType.SelectedIndex = 0;
            this.ddlAppStatus.SelectedValue = "0";

            // Binding data Buyer
            string dbType =  Utils.AppConstants.DEALER;
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, "-1");
            if (dbType.Equals(Utils.AppConstants.VSM))
            {
                txtVendorCode.Text = "MC";
                txtVendorName.Text = "MITSUBISHI CORP.";
            }
            else
            {
                txtVendorCode.Text = "VS";
                txtVendorName.Text = "VINA STAR MOTORS CORPORATION";
            }

            dtContents = BuildContents(dtContents);
            BindData(dtContents);
        }

        protected void LoadData(String poId, string NewDocType)
        {
            string dbType = Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();

            //Hieu Edit - 1/22/1014 - START
            DataSet returnDoc = new DataSet();
            if (_mrp.Length == 0 && _mrpPOId.Length == 0)
            {
                returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, poId, dbType);
                if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType);
            }
            else
            {
                MasterData obj = new MasterData();
                returnDoc = obj.GetMRPPODataById(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), _mrpPOId);
            }

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            dtHeader = returnDoc.Tables[0];
            DataRow dr = dtHeader.Rows[0];

            this.txtVendorName.Text = dr["CardName"].ToString();
            this.txtVendorCode.Text = dr["CardCode"].ToString();
            if(dtHeader.Columns.Contains("DocEntry")){
                this.txtPONo.Text = dr["DocEntry"].ToString();
            }
            this.lblStatus.Text = dr["DocStatus"].ToString();

            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")) );
            txtPODate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")) );
            txtDelDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtHeader.Rows[0]["DocDueDate"], new CultureInfo("es-US")) );

            ddlPOType.Items.FindByValue("0").Selected = false;
            ddlPOType.Items.FindByValue("1").Selected = false;
            if (ddlPOType.Items.FindByValue(dr["U_SOType"].ToString()) != null)
                ddlPOType.Items.FindByValue(dr["U_SOType"].ToString()).Selected = true;
            else ddlPOType.SelectedIndex = 0;

            ddlAppStatus.SelectedValue = dr["U_Updatestatus"].ToString();
            txtRemarks.Text = dr["Comments"].ToString();
            this.hdnDealerID.Value = dr["U_DealerID"].ToString();
            if (dr["DocStatus"].ToString().Equals("C"))
            {
                this.lblStatus.Text = "Closed";
                SetScreenStatus("Close");
            }
            else if (dr["DocStatus"].ToString().Equals("O"))
            {
                this.lblStatus.Text = "Open";
                if (NewDocType != ConvertDocType.Get2String(DocType.PURCHASE_ORDER) )
                    SetScreenStatus("New");
                else SetScreenStatus("Update");
            }

            // Binding data Buyer
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, dr["SlpCode"].ToString());
            
            dtContents = BuildContents(returnDoc.Tables[1]);
            foreach (DataRow row in dtContents.Rows)
            {
                updateRowTotalPrice(row, "");
                if (ConvertDocType.Get2String(DocType.PURCHASE_ORDER) != NewDocType) //in this case is copy to
                {
                    row["BaseEntry"] = poId;
                    row["BaseType"] = NewDocType;
                    row["BaseLine"] = row["LineNum"];
                }
            }
            BindData(dtContents);
            updateTableTotalPrice();
        }

        private void ImportData()
        {
            {
                dtContents =  (DataTable)Session["POR1Table"];

                string connectionString = string.Empty;
                if (this.FileUploadControl.HasFile)
                {
                    string fileName = Path.GetFileName(FileUploadControl.PostedFile.FileName);
                    string fileExtension = Path.GetExtension(this.FileUploadControl.PostedFile.FileName);
                    string fileLocation = Server.MapPath("~/App_Data/" + fileName);
                    this.FileUploadControl.SaveAs(fileLocation); // save file to server

                    //Check whether file extension is xls or xslx
                    if (fileExtension == ".xls")
                    {
                        connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                    }
                    else if (fileExtension == ".xlsx")
                    {
                        connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    }
                    //Create OleDB Connection and OleDb Command
                    OleDbConnection con = new OleDbConnection(connectionString);
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.Connection = con;
                    OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
                    DataTable dtExcelRecords = new DataTable();
                    con.Open();
                    DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
                    cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
                    dAdapter.SelectCommand = cmd;
                    dAdapter.Fill(dtExcelRecords);
                    con.Close();
                }

                for (int x = 1; x < this.FileLines.Count; x++)
                {
                    string[] rowData = FileLines[x].ToString().Split(',');
                    DataRow dr = dtContents.NewRow();
                    
                    dr["ItemCode"] = rowData[0];
                    dr["Dscription"] = rowData[1];
                    dr["U_Model"] = rowData[2];
                    dr["U_Color"] = rowData[3];
                    dr["UomCode"] = rowData[4];
                    dr["Quantity"] = rowData[5];
                    dr["PriceBefDi"] = rowData[6];
                    dr["DiscPrcnt"] = rowData[7];
                    //dr["Price"] = rowData["Price"]; // Price After Discount
                    //dr["LineTotal"] = dr["LineTotal"];
                    dtContents.Rows.Add(dr);
                }
            }
        }

        protected void ClearScreen()
        {
            // Binding data Buyer
            string dbType =  Utils.AppConstants.DEALER;
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, "-1");
            dtContents = new DataTable(TblLineName);
            dtContents.Columns.Add("No");
            dtContents.Columns.Add("LineNum");
            dtContents.Columns.Add("ItemCode");
            dtContents.Columns.Add("Taxcode");
            dtContents.Columns.Add("VatPrcnt");
            dtContents.Columns.Add("Dscription");
            dtContents.Columns.Add("U_Model");
            dtContents.Columns.Add("U_Color");
            dtContents.Columns.Add("UomCode");
            dtContents.Columns.Add("Quantity");
            dtContents.Columns.Add("PriceBefDi");
            dtContents.Columns.Add("DiscPrcnt");
            dtContents.Columns.Add("Price"); // Price After Discount
            dtContents.Columns.Add("LineTotal");

            dtContents.Columns.Add("BaseEntry");
            dtContents.Columns.Add("BaseLine");
            dtContents.Columns.Add("BaseType");
            
            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDelDate.Text.ToString(ci);
            txtPODate.Text.ToString(ci); // DocDate

            txtPONo.Text =
            txtRemarks.Text =
            txtConpersonName.Text = string.Empty;

            this.lblSubTotal.Text = "0";
            this.lblTaxAmount.Text = "0";
            this.lblDocumentTotal.Text = "0";

            BindData(dtContents);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnApprove.Enabled =
                    btnReject.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnIsCreatedSO.Value = "false";
                    this.hdnStatus.Value = "O";
                    break;
                case "Update":
               
                    
                        btnReject.Enabled = 
                        btnApprove.Enabled = true;
                        hdnIsUpdate.Value = "true";
                        hdnIsCreatedSO.Value = "false";
                        this.hdnStatus.Value = "O";
                    break;

                case "Close":
                    btnApprove.Enabled =
                    btnReject.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnIsCreatedSO.Value = "false";
                    this.hdnStatus.Value = "C";
                    break;
            }
        }

        public String _collectData()
        {
            try
            {
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series"); // 13
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("SlpCode");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("U_SOType");
                dtHeader.Columns.Add("U_Updatestatus");

                DataRow drHeader = dtHeader.NewRow();
                if (hdnIsUpdate.Value.Equals("true")) // Update
                {
                    drHeader["DocEntry"] =
                    drHeader["DocNum"] = int.Parse(txtPONo.Text);
                }
                else // Add new
                {
                    drHeader["Series"] = 13;
                    drHeader["DocStatus"] = "O";
                }

                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDelDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtPODate.Text).ToString("yyyyMMdd");

                drHeader["Comments"] = txtRemarks.Text;
                drHeader["CardCode"] = txtVendorCode.Text;
                drHeader["CardName"] = txtVendorName.Text;
                drHeader["U_SOType"] = ddlPOType.SelectedValue;
                drHeader["SlpCode"] = ddlBuyer.SelectedValue;
                drHeader["U_Updatestatus"] = ddlAppStatus.SelectedValue;

                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;
                
                dtContents = (DataTable)Session["POR1Table"];
                DataTable dt = new DataTable(TblLineName);
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("UomCode");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("PriceBefDi");
                dt.Columns.Add("DiscPrcnt");
                dt.Columns.Add("Price");
                dt.Columns.Add("LineTotal");

                if (dtContents != null)
                {
                    int liNo = 0;
                    foreach (DataRow dr in dtContents.Rows)
                    {
                        DataRow row = dt.NewRow();
                        if (hdnIsUpdate.Value.Equals("true")) row["DocEntry"] = int.Parse(txtPONo.Text);
                        row["LineNum"] = liNo;
                        row["LineStatus"] = "O";
                        row["ItemCode"] = dr["ItemCode"];
                        row["Dscription"] = dr["Dscription"];
                        row["U_Model"] = dr["U_Model"];
                        row["U_Product"] = dr["U_Product"];
                        row["U_Color"] = dr["U_Color"];
                        row["UomCode"] = dr["UomCode"];
                        row["Quantity"] = dr["Quantity"];
                        row["PriceBefDi"] = dr["PriceBefDi"];
                        row["DiscPrcnt"] = dr["DiscPrcnt"];
                        row["Price"] = dr["Price"]; // Price After Discount
                        row["LineTotal"] = dr["LineTotal"];
                        dt.Rows.Add(row);
                        liNo++;
                    }
                }

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                ds.Tables.Add(dtHeader.Copy());

                Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "DiscPrcnt", "LineTotal" }; // Columns need to reset format numeric
                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy());
                Session["OpenOrderQty"] = ds;
                return objInfo.ToXMLStringFromDS( ConvertDocType.Get2String(DocType.PURCHASE_ORDER), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        public String ApproveReject(string Updatestatus)
        {
            try
            {
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("U_Updatestatus");

                DataRow drHeader = dtHeader.NewRow();
                drHeader["DocEntry"] = int.Parse(txtPONo.Text);
                drHeader["Comments"] = txtRemarks.Text.Trim();
                drHeader["U_Updatestatus"] = Updatestatus;

                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                ds.Tables.Add(dtHeader.Copy());

                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.PURCHASE_ORDER), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        protected void updateTableTotalPrice()
        {
            double orderTotalBeforeDiscount = 0.0;
            double orderTotal = 0.0;
            double taxTotal = 0.0;
            foreach (DataRow row in dtContents.Rows)
            {
                if (!"".Equals(row["ItemCode"]))
                {
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["LineTotal"].ToString()), "SumDec");
                    double taxRate = GF.Object2Double( GF.ResetFormatNumeric( row["VatPrcnt"].ToString()), "RateDec");
                    if (taxRate == 0) taxRate = 10;
                    double tax = total * taxRate / 100;
                    orderTotalBeforeDiscount += total;
                    taxTotal += tax;
                }
            }

            this.lblSubTotal.Text = GF.FormatNumeric(orderTotalBeforeDiscount.ToString(), "SumDec");
            this.lblDiscAmount.Text = "0";
            this.lblTaxAmount.Text = GF.FormatNumeric(taxTotal.ToString(), "SumDec");
            orderTotal = orderTotalBeforeDiscount + taxTotal;
            this.lblDocumentTotal.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
        }

        public void updateRowTotalPrice(DataRow row, string currColName)
        {
            double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, total = 0;
            quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
            unitPrice = GF.Object2Double( GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
            discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");
            priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");

            total = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

            if (string.IsNullOrEmpty(currColName))
                row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt"))
                row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt") || currColName.Equals("Quantity"))
                row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");

            row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
            row["LineTotal"] = GF.FormatNumeric(total.ToString(), "SumDec");
            
        }

        public String CollectDataSO()
        {
            try
            {
                DataTable dtVatGroup = GF.GetVatGroupByCategory(Utils.AppConstants.VSM, "0");
                DataTable dtWhs = GF.GetWarehouseByDealerDepartment(Utils.AppConstants.VSM, Utils.AppConstants.VSM, Utils.AppConstants.PARTS);

                //Update table header
                DataTable dtHeader = new DataTable("ORDR");
                dtHeader.Columns.Add("Series"); 
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("NumAtCard");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("GrosProfit");
                dtHeader.Columns.Add("VatSum");
                dtHeader.Columns.Add("DiscSum");
                dtHeader.Columns.Add("DiscPrcnt");
                // UDF
                dtHeader.Columns.Add("U_SOType");
                dtHeader.Columns.Add("U_OrderConfirm");
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");

                DataRow drHeader = dtHeader.NewRow();
                drHeader["Series"] = 8;
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDelDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtPODate.Text).ToString("yyyyMMdd");
                drHeader["NumAtCard"] = txtPONo.Text;
                drHeader["U_SOType"] = ddlPOType.SelectedValue;
                drHeader["U_OrderConfirm"] = "0";
                drHeader["Comments"] = txtRemarks.Text;
                MasterData masterDataWS = new MasterData();
                DataSet dsDealer = masterDataWS.GetDealerByID(Utils.AppConstants.VSM, this.hdnDealerID.Value);
                if (dsDealer != null & dsDealer.Tables[0].Rows.Count == 1)
                {
                    drHeader["CardCode"] = dsDealer.Tables[0].Rows[0]["CardCode"].ToString();
                    drHeader["CardName"] = dsDealer.Tables[0].Rows[0]["CardName"].ToString();
                    drHeader["U_ContactPerson"] = dsDealer.Tables[0].Rows[0]["U_ContactPerson"].ToString();
                }

                drHeader["GrosProfit"] = GF.ResetFormatNumeric(string.IsNullOrEmpty(lblSubTotal.Text) ? "0" : lblSubTotal.Text);
                drHeader["VatSum"] = GF.ResetFormatNumeric(string.IsNullOrEmpty(lblTaxAmount.Text) ? "0" : lblTaxAmount.Text);
                drHeader["DiscSum"] =
                drHeader["DiscPrcnt"] = 0;
                //UDF
                drHeader["U_DealerID"] = Utils.AppConstants.VSM;
                drHeader["U_Department"] = Utils.AppConstants.PARTS;

                dtHeader.Rows.Add(drHeader);

                Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "LineTotal" };
                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                dtHeader.TableName = "ORDR";
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable("RDR1");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("ShipDate");
                dt.Columns.Add("Price");
                dt.Columns.Add("DiscPrcnt");
                dt.Columns.Add("LineTotal");
                dt.Columns.Add("PriceBefDi");

                dt.Columns.Add("VatGroup");
                dt.Columns.Add("VatPrcnt");
                //UDF
                dt.Columns.Add("VatSum");
                dt.Columns.Add("U_Discount");
                dt.Columns.Add("U_IncentiveDiscount");
                dt.Columns.Add("WhsCode");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Model");

                int liNo = 0;
                foreach (DataRow dr in dtContents.Rows)
                {
                    DataRow rowNew = dt.NewRow();
                    rowNew["ItemCode"] = dr["ItemCode"];
                    rowNew["Dscription"] = dr["Dscription"];
                    rowNew["Quantity"] = dr["Quantity"];
                    rowNew["Price"] = dr["Price"];
                    rowNew["DiscPrcnt"] = dr["DiscPrcnt"];
                    rowNew["LineTotal"] = dr["LineTotal"];
                    rowNew["PriceBefDi"] = dr["PriceBefDi"];
                    rowNew["VatGroup"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Code"].ToString() : string.Empty;
                    rowNew["VatPrcnt"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Rate"].ToString() : "0";
                    rowNew["U_Discount"] =
                    rowNew["U_IncentiveDiscount"] = 0;
                    rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
                    //UDF
                    rowNew["U_Color"] = dr["U_Color"];
                    rowNew["U_Product"] = dr["U_Product"];
                    rowNew["U_Model"] = dr["U_Model"];
                    dt.Rows.Add(rowNew);
                    liNo++;
                }

                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy());
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.SALES_ORDER), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            try
            {
                string lsPONo = txtPONo.Text, lsSONo = string.Empty;
                String lsBuyerCode = ddlBuyer.SelectedValue;
                String requestXMLPO = ApproveReject("1");
                String requestXMLSO = CollectDataSO();
                if (string.IsNullOrEmpty(requestXMLPO) ||  string.IsNullOrEmpty(requestXMLSO)) return;

                Transaction ts = new Transaction();
                DataSet ds = ts.UpdatePOCreateSO(requestXMLPO, txtPONo.Text, requestXMLSO);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXMLSO;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    lsSONo = ds.Tables[0].Rows[0]["ErrMsg"].ToString();
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                    // Send E-mail:
                    #region Send mail
                    SendMailApproved(lsPONo, lsSONo, lsBuyerCode);
                    #endregion
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            try
            {
                string lsPONo = txtPONo.Text;
                string lsBuyerCode = ddlBuyer.SelectedValue;
                string dbType =  Utils.AppConstants.DEALER;

                String requestXML = ApproveReject("2");
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.PURCHASE_ORDER), txtPONo.Text, true, dbType);
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    MasterData obj = new MasterData();
                    string errorMess = obj.UpdatePOMRPStatus(_mrpPOId, dbType, (DataSet)Session["OpenOrderQty"]);
                    if (_mrp.Length > 0)
                    {
                        Response.Redirect("/Business/Purchasing/CreatePO.aspx?mess=1");
                    }
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    //ClearScreen();
                    dtContents = null;
                    LoadDefault();
                    // Send E-mail: 
                    #region Send email to Buyer
                    SendMail(lsPONo, lsBuyerCode);
                    #endregion
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (!ImportValidation()) return;
        }

        private bool ImportValidation()
        {
           
            if (this.FileUploadControl.PostedFile == null && this.FileUploadControl.PostedFile.FileName.Length <= 0)
            {
                Session["errorMessage"] = "Please select a Excel file before click on Import button.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            string lsFileExtension = Path.GetExtension(this.FileUploadControl.PostedFile.FileName);
            if ( (!lsFileExtension.Equals(".xls")) & (!lsFileExtension.Equals(".xlsx")) )
            {
                Session["errorMessage"] = "Invalid file. Please select a .xls/.xlsx file.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            return true;
        }

        protected void btnCopyToGRPO_Click(object sender, EventArgs e)
        {
            Response.Redirect(TargetPageUrlGRPO + "?base_type=" + ConvertDocType.Get2String(DocType.PURCHASE_ORDER) + "&base_entry=" + txtPONo.Text);
        }

        protected void btnCopyToAPInvoice_Click(object sender, EventArgs e)
        {
            Response.Redirect(TargetPageUrlAPINV + "?base_type=" + ConvertDocType.Get2String(DocType.PURCHASE_ORDER) + "&base_entry=" + txtPONo.Text);
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsPONo = fGetDefault.GetMaxDocEntry(
                 Utils.AppConstants.DEALER, 
                Session[Utils.AppConstants.ID_Dealer].ToString(), 
                Utils.AppConstants.PARTS,
                ConvertDocType.Get2String(DocType.PURCHASE_ORDER), 
                TblHeaderName, HeaderKeyName
            );
            if (txtPONo.Text.CompareTo(lsPONo) != 0) Response.Redirect(CurrentPageUrl + "?po_id=" + lsPONo);
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                Label lblModel = (Label)row.FindControl("lblModel");
                lblModel.Text = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType =  Utils.AppConstants.DEALER;
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    Label lblProduct = (Label)row.FindControl("lblProduct");
                    lblProduct.Text = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                Label lblProduct = (Label)row.FindControl("lblProduct");
                lblProduct.Text = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                Label lblColor = (Label)row.FindControl("lblColor");
                lblColor.Text = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");

            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {
                string dbType =  Utils.AppConstants.DEALER;
                DataTable dtItem = GF.GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataSet defaultInfo = defaultWS.GetDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                        this.txtVendorCode.Text, dtItem.Rows[0]["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.PARTS);
                    if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                    {
                        DataRow drDefaultLine = defaultInfo.Tables[0].Rows[0];
                        rowUpdate = tblPOR1.Select("No=" + lblNo.Text);
                        if (rowUpdate.Length == 1)
                        {
                            rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                            rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                            rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                            rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                            rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                            rowUpdate[0]["Quantity"] = 1;

                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["UnitPrice"];
                            rowUpdate[0]["DiscPrcnt"] = drDefaultLine["Discount"];
                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["PriceAfDi"];
                            rowUpdate[0]["TaxCode"] = drDefaultLine["TaxCode"];
                            rowUpdate[0]["VatPrcnt"] = drDefaultLine["TaxRate"];

                        }
                    }
                }
                else
                {
                    rowUpdate = tblPOR1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] =
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    rowUpdate[0]["Quantity"] = 1;

                    rowUpdate[0]["PriceBefDi"] = 0;
                    rowUpdate[0]["DiscPrcnt"] = 0;
                    rowUpdate[0]["PriceBefDi"] = 0;
                    rowUpdate[0]["TaxCode"] = string.Empty;
                    rowUpdate[0]["VatPrcnt"] = 0;
                }
                BindData(tblPOR1);
            }
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tbPOR1 = (DataTable)Session["POR1Table"];
            DataRow rowNew = tbPOR1.NewRow();
            rowNew["No"] = (tbPOR1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] =
            rowNew["Dscription"] =
            rowNew["U_Model"] =
            rowNew["U_Product"] =
            rowNew["U_Color"] = string.Empty;
            rowNew["Quantity"] = 1;
            rowNew["PriceBefDi"] = 0;
            rowNew["DiscPrcnt"] = 0;
            rowNew["PriceBefDi"] = 0;
            rowNew["TaxCode"] = string.Empty;
            rowNew["VatPrcnt"] = 0;
            tbPOR1.Rows.Add(rowNew);
            BindData(tbPOR1);
        }

        private void SendMail(string PONo, string BuyerCode)
        {
            if (ConfigurationManager.AppSettings["EmailActive"].ToString().CompareTo("0") == 0) return;

            try
            {
                string dbType =  Utils.AppConstants.DEALER;
                string MailContent = string.Empty, MailTitle = string.Empty;
                EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.PORejected, "en");

                MasterData obj = new MasterData();
                DataSet dsSaleMan = obj.GetSalesManByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), BuyerCode);
                DataSet dsSaleManager = obj.GetManagerBySaleManCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), BuyerCode);
                if (dsSaleMan != null && dsSaleMan.Tables[0].Rows.Count > 0 && dsSaleManager != null && dsSaleManager.Tables[0].Rows.Count > 0)
                {
                    MailContent = CurMailGenerator.PORejected(dsSaleMan.Tables[0].Rows[0]["SlpName"].ToString(), PONo, dsSaleManager.Tables[0].Rows[0]["SlpName"].ToString(), ConfigurationManager.AppSettings["VSM_URL"].ToString());
                    MailTitle = CurMailGenerator.MailTitle;
                    string[] tos = new string[] { dsSaleMan.Tables[0].Rows[0]["U_Email"].ToString(), dsSaleManager.Tables[0].Rows[0]["U_Email"].ToString() };
                    Emails.SendEmail(tos, MailTitle, MailContent, null, null);
                }
            }
            catch (Exception ex)
            {
                // Add eeror to log.
            }
        }

        private void SendMailApproved(string PONo, string SONo, string BuyerCode)
        {
            if (ConfigurationManager.AppSettings["EmailActive"].ToString().CompareTo("0") == 0) return;

            try
            {
                string dbType =  Utils.AppConstants.DEALER;
                string MailContent = string.Empty, MailTitle = string.Empty;

                string[] tos = null;
                MasterData obj = new MasterData();
                EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.POApproved, "en");

                DataSet dsBuyer = obj.GetSalesManByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), BuyerCode);
                DataSet dsBuyManager = obj.GetManagerBySaleManCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), BuyerCode);

                // Send mail for Buyer and Buy Manager Dealer
                if (dsBuyer != null && dsBuyer.Tables[0].Rows.Count > 0 && dsBuyManager != null && dsBuyManager.Tables[0].Rows.Count > 0)
                {
                    MailContent = CurMailGenerator.POApproved(dsBuyer.Tables[0].Rows[0]["SlpName"].ToString(), PONo, dsBuyManager.Tables[0].Rows[0]["SlpName"].ToString(), ConfigurationManager.AppSettings["VSM_URL"].ToString());
                    MailTitle = CurMailGenerator.MailTitle;
                    tos = new string[] { dsBuyer.Tables[0].Rows[0]["U_Email"].ToString(), dsBuyManager.Tables[0].Rows[0]["U_Email"].ToString() };
                    Emails.SendEmail(tos, MailTitle, MailContent, null, null);
                }

                // Send mail for Sale Man and Sale Manager
                string lsDealerName = String.Empty;
                DataSet dsDealer = obj.GetDealerByID(dbType, Session[AppConstants.ID_Dealer].ToString());
                if (dsDealer != null && dsDealer.Tables[0].Rows.Count > 0) lsDealerName = dsDealer.Tables[0].Rows[0]["CardName"].ToString();

                CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.SOSubmitted, "en");
                string[] VSMSaleMan = ConfigurationManager.AppSettings["VSMSaleSupervisor"].ToString().Split(',');
                string[] VSMSaleManager = ConfigurationManager.AppSettings["VSMSaleManager"].ToString().Split(',');
                MailContent = CurMailGenerator.SOSubmmitted(VSMSaleMan[0], VSMSaleManager[0], SONo, dsBuyManager.Tables[0].Rows[0]["SlpName"].ToString(), lsDealerName, ConfigurationManager.AppSettings["VSM_URL"].ToString());
                MailTitle = CurMailGenerator.MailTitle;
                tos = new string[] { VSMSaleMan[1], VSMSaleManager[1] };
                Emails.SendEmail(tos, MailTitle, MailContent, null, null);
            }
            catch (Exception ex)
            {
                // Add eeror to log.
            }
        }

    }
}